<template>
    <div>
        <!-- 卡片区域-->
        <el-card> 
            <!-- 上边的搜索栏-->
            <el-row :gutter="20">
                <el-col :span="10">
                    <el-input  v-model="queryInfo.query"  clearable  @clear="getUserList"  placeholder="请输入内容" >
                        <el-button   @click="getUserList"  icon="el-icon-search"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button @click="addUserdialogVisible=true"   type="primary">添加线索</el-button>
                </el-col>
            </el-row>

            <!-- 列表区域-->
            <el-table :data='userList' border stripe >
                <el-table-column lable='#' type=index> </el-table-column>
                    <el-table-column prop="username" label="线索id" > </el-table-column>
                    <el-table-column prop="email" label="线索名称" > </el-table-column>
                    <el-table-column prop="mobile"  label="所属销售"> </el-table-column>
                    <el-table-column prop="role_name"  label="联系人"> </el-table-column>
                    <el-table-column prop="mg_state"  label="联系电话"> 
                        <template  >
                            <el-switch v-model="scope.row.mg_state" @change="getUserState(scope.row)">
                            </el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column   label="操作" width="200px"> 
                        <template >
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removerUserById(scope.row.id)"></el-button>
                            <el-tooltip class="item" effect="dark" content="联系人" placement="top">
                                <el-button @click="showSetRoleDialog(scope.row)" size="mini" type="warning" icon="el-icon-setting"></el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
            </el-table>
            <!-- 分页区域-->
            <el-pagination @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1,3,5]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>
        <!-- 弹出添加线索操作-->
        <el-dialog   @close="addDialogClose"  title="添加线索" :visible="addUserdialogVisible" width="50%">
            <el-form    :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px" >
                <el-form-item label="线索名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="所属销售" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="联系人" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="联系电话" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span class="dialog-footer">
                <el-button @click="addDialogVisable= false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog   @close="editDialogClose"  title="修改线索信息" :visible="editVisible" width="50%">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" >
                <el-form-item label="线索名"  >
                    <el-input v-model="editForm.username" disabled ></el-input>
                </el-form-item>
                <el-form-item label="所属销售" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="联系人" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span  class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo">确 定</el-button>
            </span>
        </el-dialog>
         <!-- 为线索分配角色-->
        <el-dialog @close="setRoleDialogClose" title="联系人" :visible="setRoleDialogVisible" width="50%">
            <p>线索名：{{userId.username}}</p>
            <p>当前联系人：{{userId.role_name}}</p>
            <p>联系人
                <el-select v-model="selectedRoleId" placeholder="请选择">
                    <el-option
                        v-for="item in roleList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                    </el-option>
                </el-select>
            </p>
            <span class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRoleConfirm">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>   

<script>
export default {
    data(){
        return{
            //获取线索列表的参数对象
            queryInfo:{
                query:'',//这个是个空的
                pagenum: 1,
                pagesize: 3
            },
            // 存放线索的数据和数量
            userList:[

            ],
            total:1,
            addUserdialogVisible:false,
            addForm:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            addFormRules:{
                username:[
                    { required: true, message: '请输入线索名', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                mobile:[
                    { required: true, message: '请输入手机', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ]},
            editVisible:false,
            editForm:{
                    username:'',
                    email:'',
                    mobile:''
                },
            editFormRules:{
                    email:[
                        { required: true, message: '请输入邮箱', trigger: 'blur' },
                        { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                    ],
                    mobile:[
                        { required: true, message: '请输入手机', trigger: 'blur' },
                        { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                    ]},
            setRoleDialogVisible:false,
            setRoleDialogList:[],
            userId:[],
            roleList:[],
            selectedRoleId:'',
             
        }
    },

    created(){
        this.getUserList()
    },

    methods:{
        async getUserList(){
            const { data: res}= await this.$http.get('users',{params:this.queryInfo})
            if(res.meta.status!==200) return this.$message.error("获取线索列表失败")
            console.log(res)
            this.userList= res.data.users 
            this.total=res.data.total
        },
        handleSizeChange(newSize){
            this.queryInfo.pagesize=newSize
            this.getUserList()
        },
        handleCurrentChange(newPage){
            this.queryInfo.pagenum=newPage
            this.getUserList()
        },
        //监听switch的变化
        async getUserState(userInfo){
            const {data:res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
            if(res.meta.status!==200) {
                userInfo.mg_state=!userInfo.mg_state
                return this.$message.error("线索状态修改失败")
            }
 
            this.$message.success("线索状态修改成功")
        },
        //监听对话框关闭
        addDialogClose(){
            this.$refs.addFormRef.resetFields()
        },
        addUser(){
            this.$refs.addFormRef.validate(async valide=>{
                if(!valide) return
                const {data:res}= await this.$http.post('users',this.addForm)
                console.log(res)
                if(res.meta.status!==201)  {
                    this.$message.error("添加失败")
                } 
                this.$message.success("添加成功")
                this.addUserdialogVisible = false
                this.getUserList()
            })
        },
        async showEditDialog(id){
            const {data:res} = await this.$http.get('users/'+id)
            if(res.meta.status!=200){
                return this.$message.error("获取失败")
            }
            this.editForm = res.data
            this.editVisible=true
        },
        editDialogClose(){
            this.$refs.editFormRef.resetFields()
        },
        editUserInfo(){
            this.$refs.editFormRef.validate(async valide=>{
                if(!valide) return
                const {data:res}= await this.$http.put('users/'+this.editForm.id,{email:this.editForm.email,mobile:this.editForm.mobile})
                if(res.meta.status!==200){
                    return this.$message.error("更新失败")
                }
                this.editVisible=false
                this.getUserList()
                this.$message.success("更新成功")
            })
        },
        async removerUserById(id){
            console.log(id)
            //弹框提示是否删除
            const confirmResult = await this.$confirm('此操作将永久删除该线索, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).catch(err=>err)

                if(confirmResult!=='confirm'){
                    return this.$message.info("取消删除")
                }
                const {data:res} =await this.$http.delete('users/'+id)
                
                if(res.meta.status!==200){
                    return this.$message.error("删除线索失败")
                }
                this.$message.sucess("删除线索成功")
                this.getUserList()
                
        },
        async showSetRoleDialog(userId){
            this.userId=userId//获得该行的数据
            //获取角色列表，传递给data中得roleList的值
            //（在弹出对话框之前就已经有所有角色的数据了，所以不用单独定义函数）
            const {data:res} = await this.$http.get('roles')
            if(res.meta.status!==200){
                return this.$message.error("获取角色列表失败")
            }
            this.roleList=res.data
            this.setRoleDialogVisible = true
        },
        async setRoleConfirm(){
            if(!this.selectedRoleId){
                return this.$message.error("请选择角色")
            }
            const{data:res} = await this.$http.put(`users/${this.userId.id}/role`,{rid: this.se})
            if(res.meta.status!==200){
                return this.$message.error("添加角色失败")
            }
            this.getUserList()
            this.setRoleDialogVisible = false
        },
        setRoleDialogClose(){
            this.selectedRoleId=''
        },


         
    }
    
}
</script>script

<style  scoped>

</style>